import './setEnvVars';
import prisma from '../lib/prisma';

interface TableInfo {
  tablename: string;
}

async function globalSetup(): Promise<void> {
  if (process.env.SKIP_DB_CLEAN !== 'true') {
    try {
      // 尝试数据库连接
      await prisma.$connect();
      
      // 清理数据库
      const tablenames = await prisma.$queryRaw<TableInfo[]>`
        SELECT tablename 
        FROM pg_tables
        WHERE schemaname='public'
      `;

      const tables = tablenames
        .map(({ tablename }: TableInfo) => tablename)
        .filter((name: string) => !name.includes('_prisma_'))
        .filter((name: string) => !name.includes('schema_migrations'));

      await prisma.$transaction([
        prisma.$executeRawUnsafe('SET CONSTRAINTS ALL DEFERRED'),
        ...tables.map((table: string) => 
          prisma.$executeRawUnsafe(`TRUNCATE TABLE "${table}" CASCADE`)
        ),
        prisma.$executeRawUnsafe('SET CONSTRAINTS ALL IMMEDIATE'),
      ]);
    } catch (error) {
      console.warn('Database cleanup skipped:', error);
      // 不抛出错误，允许测试继续运行
    } finally {
      await prisma.$disconnect();
    }
  }
}

export default globalSetup;
